//引入重置样式
require('../../assets/css/reset.css')

//引入公共样式
require('../../assets/css/property.css')

//引入登录页面less
require('./login.less')

//引入封装的dom
require('../../assets/js/dom.js')

//引入请求实例
const request = require('../../utils/request')

//等待dom加载完毕之后操作dom
document.ready(() => {
    //获取dom
    const account = document.querySelector('#account');
    const pwd = document.querySelector('#pwd');
    const btn = document.querySelector('#btn');
    const msg = document.querySelector('#msg');

    function getMsg() {
        //如果错误显示信息提示框
        msg.style.display = 'block';

        // 计时器，1秒之后隐藏信息提示框
        setTimeout(() => {
            msg.style.display = 'none';
        }, 1000);
    }

    //事件注册
    btn.addEventListener('click', () => {
        //正则验证
        if (!/^1[3-9]\d{9}$/.test(account.value)) {
            getMsg();
            msg.innerHTML = '手机号格式不正确';
        } else if (!/^[0-9]{6}$/.test(pwd.value)) {
            getMsg();
            msg.innerHTML = '请输入0-9的6位密码';
        } else {
            request.post('/api/user/login', {
                account: account.value,
                password: pwd.value
            }).then(res => {
                //1 解构数据
                let { errno, data, message } = res.data;
                //2 判断
                if (errno === 0) {
                    //3 处理数据
                    localStorage.setItem('token', 'Bearer ' + data.token);
                    // 渲染到页面
                    msg.innerHTML = '登录成功';
                    //显示信息提示框
                    msg.style.display = 'block';
                    // 计时器 1s后跳转到首页
                    setTimeout(() => {
                        location.href = './home.html';
                    }, 1000);
                } else {
                    getMsg();
                    msg.innerHTML = message;
                }
            })
        }
    })
})